<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/1/31
 * Time: 20:24
 * Desc: 会员相关功能服务
 */
namespace app\index\service;
use think\Controller;
use think\Db;
use Wechat\Lib\Tools;
use Wechat\Lib\Common;      //微信公共类
use think\Loader;           //自动加载类
use gmars\qiniu\Qiniu;      //七牛云

class UserOtherService extends Controller{
    /**
     * @Author  lingyun
     * @Desc    我的收货地址
     */
    public function my_address(){
        $uid = session('_user_uid_.uid');
        $list = db('user_address')->where('uid',$uid)->select();        //我的收货地址
        $this->assign('list',$list);
    }

    /**
     * @Author  lingyun
     * @Desc    添加 -- 编辑收货地址
     */
    public function add_edit_address(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            $post['uid'] = session('_user_uid_.uid');
            $reg = '/^1[34578]\d{9}$/';
            if(empty($post['consignee'])){
                $this->error('请填写收货人姓名','');
            }
            if(empty($post['province'])){
                $this->error('请填写省份','');
            }
            if(empty($post['city'])){
                $this->error('请填写城市','');
            }
            if(empty($post['area'])){
                $this->error('请填写地区','');
            }

            if(empty($post['address'])){
                $this->error('请填写详细地址','');
            }
            if(empty($post['mobile'])){
                $this->error('请填写手机号','');
            }
            if(!preg_match($reg,$post['mobile'])){
                $this->error('手机格式输入错误','');
            }

            //检查收货地址是否正确
            $res = check_address($post['address']);
            if($res['code'] == 0){
                return json(['code'=>0,'msg'=>$res['msg']]);
            }else{
                $post['lng'] = $res['data']['lng'];     //经度
                $post['lat'] = $res['data']['lat'];     //纬度
            }

            if(empty($post['id'])){
                unset($post['id']);
                if($post['is_default'] == 1){
                    db('user_address')->where('uid',session('_user_uid_.uid'))->setField('is_default',0);
                }else{
                    $is_default = db('user_address')->where(['uid'=>session('_user_uid_.uid'),'is_default'=>1])->find();
                    if(empty($is_default)){
                        $post['is_default'] = 1;
                    }
                }

                $res = db('user_address')->data($post)->insert();
                if($res > 0){
                    $this->success('保存成功','');
                }else{
                    $this->error('保存失败','');
                }
            }else{
                $res = db('user_address')->update($post);
                if($res !== false){
                    $this->success('保存成功','');
                }else{
                    $this->error('保存失败','');
                }
            }
        }
        $id = input('id');
        $address = db('user_address')->where('id',$id)->find();

        $this->assign('id',$id);
        $this->assign('address',$address);
    }

    /**
     * @Author  lingyun
     * @Desc    将地址设置为默认地址
     */
    public function set_address_default(){
        $id = input('id');
        db('user_address')->where('uid',session('_user_uid_.uid'))->setField('is_default',0);
        $res = db('user_address')->where('id',$id)->setField('is_default',1);
        $res!==false?$this->success('设置成功',''):$this->error('设置失败');
    }

    /**
     * @Author  lingyun
     * @Desc    取消默认地址
     */
    public function cancel_address_default(){
        $id = input('id');
        $res = db('user_address')->where('id',$id)->setField('is_default',0);
        $res!==false?$this->success('取消成功',''):$this->error('取消失败','');
    }

    /**
     * @Author  lingyun
     * @Desc    我的优惠券
     *          type   1未使用，2未领取，3已使用，4已过期
     */
    public function my_coupon(){
        $type = empty(input('type'))?1:input('type');      //未使用  已使用  已过期
        $time = time();
        $store_id = cookie('store_id');
        $uid = session('_user_uid_.uid');
        if($type == 1){         //未使用
            $where = [
                'a.uid'=>$uid,
                'a.is_used'=>0,
                'b.store_id'=>$store_id,
//                'a.type'=>['neq',2],
                'a.use_end_time'=>['gt',time()],
                'b.is_deleted'=>0,
                'b.status'=>1
            ];
            $list = db('user_ycard')->alias('a')->join('ys_store_coupon b','a.coupon_id=b.id','LEFT')->join('ys_goods_category c','a.cat_id=c.id','LEFT')->where($where)->field('a.type,a.condition,a.morethan,a.reduce,a.value,a.use_start_time,a.use_end_time,b.name,b.img,b.id,c.title')->select();

        }else if($type == 2){           //未领取
            $ids = db('user_ycard')->where(['uid'=>session('_user_uid_.uid'),'store_id'=>cookie('store_id')])->column('coupon_id');
            $where = [
                'a.store_id'=>$store_id,
//                'a.type'=>['neq',2],
                'a.use_end_time'=>['gt',time()],
                'a.id'=>['not in',$ids]
            ];
            $list = db('store_coupon')->alias('a')->join('ys_goods_category b','a.cat_id=b.id','LEFT')->field('a.type,a.condition,a.morethan,a.reduce,a.value,a.use_start_time,a.use_end_time,a.name,a.img,a.id,b.title')->where($where)->select();
        }else if($type == 3){           //已使用
            $where = [
                'a.uid'=>$uid,
                'b.store_id'=>$store_id,
                'a.is_used'=>1,
//                'a.type'=>['neq',2]
            ];
            $list = db('user_ycard')->alias('a')->join('ys_store_coupon b','a.coupon_id=b.id','LEFT')->join('ys_goods_category c','a.cat_id=c.id','LEFT')->where($where)->field('a.type,a.condition,a.morethan,a.reduce,a.value,a.use_start_time,a.use_end_time,b.name,b.img,b.id,c.title')->select();
        }else{          //已过期
            $where = [
                'a.uid'=>$uid,
                'b.store_id'=>$store_id,
                'a.is_used'=>1,
//                'a.type'=>['neq',2],
                'a.use_end_time'=>['lt',time()]
            ];
            $list = db('user_ycard')->alias('a')->join('ys_store_coupon b','a.coupon_id=b.id','LEFT')->join('ys_goods_category c','a.cat_id=c.id','LEFT')->where($where)->field('a.type,a.condition,a.morethan,a.reduce,a.value,a.use_start_time,a.use_end_time,b.name,b.img,b.id,c.title')->select();
        }
        $this->assign('type',$type);
        $this->assign('nowtime',time());
        $this->assign('list',$list);
    }

    /**
     * @Author  lingyun
     * @Desc    领取优惠券
     */
    public function receive_coupon(){
        $id = input('id');
        if(empty(session('_user_uid_.uid'))){
            $this->error('您目前还未登录，请先登录','');
        }
        $receive = db('user_ycard')->where(['uid'=>session('_user_uid_.uid'),'coupon_id'=>$id])->find();
        $info = db('store_coupon')->where('id',$id)->find();
        if(!empty($receive)){
            $this->error('您已领取该优惠券，请勿重复领取','');
        }
        $data_arr = [
            'uid'=>session('_user_uid_.uid'),
            'store_id'=>cookie('store_id'),
            'coupon_id'=>$id,
            'order_id'=>0,
            'receive_order_id'=>0,
            'used_time'=>0,
            'type'=>$info['type'],
            'cat_id'=>$info['cat_id'],
            'condition'=>$info['condition'],
            'morethan'=>$info['morethan'],
            'reduce'=>$info['reduce'],
            'use_start_time'=>$info['use_start_time'],
            'use_end_time'=>$info['use_end_time'],
            'addtime'=>time(),
            'price'=>0,
            'value'=>0,
            'is_used'=>0,
            'status'=>1
        ];
        $res = db('user_ycard')->insert($data_arr);
        db('store_coupon')->where('id',$info['id'])->update(['send_num'=>$info['send_num']+1]);
        $res>0?$this->success('领取成功',''):$this->error('领取失败','');
    }

    /**
     * @Author  lingyun
     * @Desc    我收藏的商品
     */
    public function my_collect(){
        $where = [
            'a.uid'=>session('_user_uid_.uid'),
            'a.store_id'=>cookie('store_id'),
            'a.status'=>1,
            'b.is_deleted'=>0,
            'b.status'=>1
        ];
        $join = [
            ['ys_goods b','a.goods_id=b.id','LEFT']
        ];
        $list = db('user_collect')->alias('a')->join($join)->field('a.id,a.uid,a.store_id,a.goods_id,b.name,b.logo,b.price')->where($where)->paginate(10,false,['query'=>request()->param()]);
        $count = db('user_collect')->alias('a')->join($join)->count();
        $cur_page = empty(input('page'))?1:input('page');           //当前的页码
        $page = $list->render();
        $all_list= $list->all();
        $this->assign('list',$list);
        $this->assign('page',$page);
        $this->assign('all_page',ceil($count/15));
        $this->assign('cur_page',$cur_page);
        $this->assign('all_list',$all_list);
    }

    /**
     * @Author  lingyun
     * @Desc    获取ajax页面加载数据
     * @Param   $page   当前页面
     * 2018-05-05
     */
    public function get_ajax_collect($page){
        $page = $page+1;
        $where = [
            'a.uid'=>session('_user_uid_.uid'),
            'a.store_id'=>session('storer_id'),
            'a.status'=>1,
            'b.is_deleted'=>0,
            'b.status'=>1
        ];
        $join = [
            ['ys_goods b','a.goods_id=b.id','LEFT']
        ];
        $result = db('user_collect')->alias('a')->join($join)->field('a.id,a.uid,a.store_id,a.goods_id,b.name,b.logo,b.price')->page($page,15)->select();
        if(empty($result)){     //到底了
            $this->success($page-1,'',$result);
        }
        $this->success($page,'',$result);
    }

    /**
     * @Author  lingyun
     * @Desc    我的邀请二维码
     */
    public function my_invite_qrcode(){
        $uid = session('_user_uid_.uid');
        $user = db('user')->where('uid',$uid)->find();
        $root = request()->domain();
        $url = $root.url('Register/register')."?sharer={$uid}";
        if(empty($user['logo'])){
            $logo = '';
        }else{
            $logo = $user['logo'];
        }

        $this->assign('url',$url);
        $this->assign('logo',$logo);
        $this->assign('user',$user);
    }

    /**
     * @Author  lingyun
     * @Desc    生成会员的条形码
     * @param $content  条形码编号
     */
    public function pay_code($content){
        // 引用barcode文件夹对应的类
        Loader::import('BCode.BCGFontFile',EXTEND_PATH);
//        Loader::import('BCode.BCGColor',EXTEND_PATH);
        Loader::import('BCode.BCGDrawing',EXTEND_PATH);
        // 条形码的编码格式
        Loader::import('BCode.BCGcode39',EXTEND_PATH,'.barcode.php');
        // $code = '';
        // 加载字体大小
//        $font = new \BCGFontFile('./class/font/arial.ttf',18);
        //颜色条形码
        $color_black = new \BCGColor(0, 0, 0);
        $color_white = new \BCGColor(255, 255, 255);

        $drawException = null;
        try
        {
            $code = new \BCGcode39();
            $code->setScale(2);
            $code->setThickness(60); // 条形码的厚度
            $code->setForegroundColor($color_black); // 条形码颜色
            $code->setBackgroundColor($color_white); // 空白间隙颜色
//             $code->setFont($font); //
            $code->parse($content); // 条形码需要的数据内容
        }
        catch(\Exception $exception)
        {
            $drawException = $exception;
        }

        //根据以上条件绘制条形码
        $drawing = new \BCGDrawing('', $color_white);
        if($drawException) {
            $drawing->drawException($drawException);
        }else{
            $drawing->setBarcode($code);
            $drawing->draw();
        }
        // 生成PNG格式的图片
        header('Content-Type: image/png');
//         header('Content-Disposition:attachment; filename="barcode.png"'); //自动下载
        $drawing->finish(\BCGDrawing::IMG_FORMAT_PNG);
    }

    /**
     * 微信分享 -- 获取参数
     * @param  [type] $appid     公众号appid
     * @param  [type] $appsecret 公众号appsecret
     * @param  [type] $sys
     * @param  [type] $db        [description]
     * @return [type]            [description]
     */
    public function wxShare($url='') {
        $config = [
            'token' => sysconf('wechat_token'),
            'appid' => sysconf('wechat_appid'),
            'appsecret' => sysconf('wechat_appsecret'),
            'encodingaeskey' => sysconf('wechat_encodingaeskey'),
        ];

        $common = new Common($config);
        $jsapiTicket = $this->getJsApiTicket($common);
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $cur_url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";     //当前页面的url

//        $url = empty($url)?$cur_url:$url;

        $timestamp = time();
        $nonceStr = Tools::createNoncestr(16);       //获取16位随机字符串
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$cur_url";
        $signature = sha1($string);
        $signPackage = array(
            "appId"     => $common->appid,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $cur_url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }
    /**
     * @Author lignyun
     * @Desc    获取参数
     * @param   $common   微信公共类实例
     * @return
     */
    private function getJsApiTicket($common) {
        $accessToken = $common->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
        $res = json_decode(Tools::httpGet($url),true);
        $ticket = $res['ticket'];
        return $ticket;
    }

    /**
     * @Author  lingyun
     * @Desc    会员余额记录
     * 2018-03-21
     */
    public function user_credit_log(){
        $cur_page = empty(input('page'))?1:input('page');           //当前的页码
        $uid = session('_user_uid_.uid');
        $list = db('user_wallet_log')->where(['uid'=>$uid,'pay_status'=>1])->order('id desc')->paginate(15,false,['query'=>request()->param()]);
        $count = db('user_wallet_log')->where(['uid'=>$uid,'pay_status'=>1])->count();
        $page = $list->render();
        $this->assign('page',$page);
        $this->assign('list',$list);
        $this->assign('all_page',ceil($count/15));
        $this->assign('cur_page',$cur_page);
    }

    /**
     * @Author  lingyun
     * @Desc    ajax查询获取余额记录
     * @Param   当前的页码
     * 2018-05-03
     */
    public function get_ajax_wallet_log($page){
        $page = $page+1;
//        $result = db('goods_comment')->alias('a')->join('ys_user b','a.uid=b.uid','LEFT')->where(['a.goods_id'=>$goods_id,'a.is_show'=>1,'a.is_deleted'=>0])->field('a.*,b.realname,b.logo,FROM_UNIXTIME(a.addtime,"%Y-%m-%d" ) as add_time')->page($page,2)->select();
        $result = db('user_wallet_log')->alias('a')->where(['a.uid'=>session('_user_uid_.uid'),'a.pay_status'=>1])->field('a.*,FROM_UNIXTIME(a.addtime,"%Y-%m-%d") as add_time')->page($page,15)->select();
        if(empty($result)){     //到底了
            $this->success($page-1,'',$result);
        }
        $this->success($page,'',$result);
    }

    /**
     * @Author  lingyun
     * @Desc    获取会员充值类型
     * 2018-05-02
     */
    public function get_recharge_type(){
        $list =  db('sys_level')->order('id desc')->select();
        foreach($list as $k=> $v){
            $list[$k]['detail'] = htmlspecialchars_decode($v['detail']);
        }
        $this->assign('list',$list);
    }

    /**
     * @Author  lingyun
     * @Desc    会员充值
     * @param $param    充值参数
     * 2018-05-02
     */
    public function pre_pay_recharge($param){
        $reg = '/^\d+(\.\d{1,2})?$/';       //匹配金额
        $amount = 0;        //充值金额

        if(!empty($param['type_id'])){     //快捷充值方式
            $rule = db('sys_level')->where('id',$param['type_id'])->find();
            $amount = $rule['score'];
        }else{
            if(empty($param['price'])){
                return ['code'=>0,'err_msg'=>'请输入充值金额','err_url'=>url('User/recharge'),'err_button'=>'充值'];
            }else if(!preg_match($reg,$param['price'])){
                return ['code'=>0,'err_msg'=>'充值金额输入错误，请重新填写','err_url'=>url('User/recharge'),'err_button'=>'充值'];
            }
            $amount = $param['price'];
        }
        if($param['pay_type'] == ''){
            return ['code'=>0,'err_msg'=>'请选择支付方式','err_url'=>url('User/recharge'),'err_button'=>'充值'];
        }
        $member = db('user')->where('uid',session('_user_uid_.uid'))->find();

        //订单编号
        $order_sn = create_order_sn(session('_user_uid_.uid'));
        //会员充值变更记录
        $data = [
            'uid'=>session('_user_uid_.uid'),
            'store_id'=>cookie('store_id'),
            'order_id'=>0,
            'order_sn'=>$order_sn,
            'pay_status'=>0,
            'pay_type'=>$param['pay_type'],
            'amount'=>$amount,
            'give_away_amount'=>0,
            'cur_amount'=>$member['user_money']+$amount,
            'sign'=>2,
            'chargetype'=>2,
            'charge_cn'=>'余额充值',
            'addtime'=>time()
        ];
        $res = db('user_wallet_log')->insertGetId($data);
        return ['code'=>1,'order_sn'=>$order_sn,'pay_type'=>$param['pay_type']];
    }

    /**
     * @Author      Hybrid
     * @DateTime    2018-05-04
     * @Description 我的积分排行榜
     * @return      [type]     [description]
     *              1日榜  2周榜  3月榜  4年榜
     */
    public function get_point_rank($type){
        $uid = session('_user_uid_.uid');
        $store_id = cookie('store_id');         //门店
        $store = db('store')->where('id',$store_id)->find();
        $user = db('user')->where('uid',$uid)->field('uid,logo,realname')->find();
        if($type == 2){               //年榜
            $data = $this->get_week();
            $sql = "SELECT obj_new.*,a.realname,a.logo,a.mobile FROM ys_user as a left join ((SELECT obj.uid, obj.timestampsum, @rownum := @rownum + 1 AS num_tmp, @incrnum := CASE WHEN @rowtotal = obj.timestampsum THEN @incrnum WHEN @rowtotal := obj.timestampsum THEN  @rownum END AS rownum FROM   (SELECT uid, sum(point) as timestampsum, addtime FROM  `ys_user_point_log` where  addtime>".$data['start']." and addtime<".$data['end']." group by uid order by timestampsum desc ) AS obj , ( SELECT @rownum := 0 ,@rowtotal := NULL ,@incrnum := 0 ) r order by timestampsum desc ) AS obj_new) on obj_new.uid=a.uid  order by  timestampsum desc ";

//            $sql = "SELECT obj.timestampsum,a.uid,a.mobile,a.realname,@rownum := @rownum + 1 AS rownum FROM ys_user as a right join (SELECT uid, sum(point) as timestampsum, addtime FROM  `ys_user_point_log` where  addtime>".$data['start']." and addtime<".$data['end']." group by uid order by timestampsum desc ) AS obj on a.uid=obj.uid, (SELECT @rownum := 0) r ";

            $list = Db::query($sql);
            $last = end($list);
            $uid = session('_user_uid_.uid');
            $paihang = array_filter($list, function($t) use ($uid) { return $t['uid'] == $uid; });
            $list = array_slice($list,0,10);
            foreach($list as $k => $v){
                if($k == 1){
                    $list[$k]['rownum'] = 2;
                    continue;
                }
                if($k == 2){
                    $list[$k]['rownum'] = 3;
                    continue;
                }
                if($k != 0){
                    $up_k = $k-1;
                    if($v['timestampsum'] == $list[$up_k]['timestampsum']){
                        $list[$k]['rownum'] = $list[$up_k]['rownum'];
                    }else{
                        $list[$k]['rownum'] = $list[$up_k]['rownum']+1;
                    }
                }else{
                    $list[$k]['rownum'] = 1;
                }
            }

            if(!empty(array_values($paihang))){
//                $this->assign('paihang',array_values($paihang));
                $paihang = array_values($paihang);
                $paihang[0]['rownum'] = $paihang[0]['rownum'] - 1;
                $this->assign('paihang',$paihang);
            }else{
                if($last['rownum'] == ''){
                    $last = end($list);
                }
                $paihang[0]['rownum'] = $last['rownum']+1;
                $paihang[0]['logo'] = $user['logo'];
                $this->assign('paihang',$paihang);
            }

            $this->assign('list',$list);

            unset($list[0]);
            unset($list[1]);
            unset($list[2]);
            $this->assign('m_list',$list);
        }else if($type == 3){       //月榜
            $data = $this->getMonth();
            $sql = "SELECT obj_new.*,a.realname,a.logo,a.mobile FROM ys_user as a left join ((SELECT obj.uid, obj.timestampsum, @rownum := @rownum + 1 AS num_tmp, @incrnum := CASE WHEN @rowtotal = obj.timestampsum THEN @incrnum WHEN @rowtotal := obj.timestampsum THEN  @rownum END AS rownum FROM   (SELECT uid, sum(point) as timestampsum, addtime FROM  `ys_user_point_log` where  addtime>".$data['start']." and addtime<".$data['end']." group by uid order by timestampsum desc ) AS obj , ( SELECT @rownum := 0 ,@rowtotal := NULL ,@incrnum := 0 ) r order by timestampsum desc ) AS obj_new) on obj_new.uid=a.uid  order by  timestampsum desc ";
//            $sql = "SELECT obj.timestampsum,a.uid,a.mobile,a.realname,@rownum := @rownum + 1 AS rownum FROM ys_user as a right join (SELECT uid, sum(point) as timestampsum, addtime FROM  `ys_user_point_log` where  addtime>".$data['start']." and addtime<".$data['end']." group by uid order by timestampsum desc ) AS obj on a.uid=obj.uid, (SELECT @rownum := 0) r ";

            $list = Db::query($sql);
            $last = end($list);
            $uid = session('_user_uid_.uid');
            $paihang = array_filter($list, function($t) use ($uid) { return $t['uid'] == $uid; });
            $list = array_slice($list,0,10);
            foreach($list as $k => $v){
                if($k == 1){
                    $list[$k]['rownum'] = 2;
                    continue;
                }
                if($k == 2){
                    $list[$k]['rownum'] = 3;
                    continue;
                }
                if($k != 0){
                    $up_k = $k-1;
                    if($v['timestampsum'] == $list[$up_k]['timestampsum']){
                        $list[$k]['rownum'] = $list[$up_k]['rownum'];
                    }else{
                        $list[$k]['rownum'] = $list[$up_k]['rownum']+1;
                    }
                }else{
                    $list[$k]['rownum'] = 1;
                }
            }

            if(!empty(array_values($paihang))){
                $paihang = array_values($paihang);
                $paihang[0]['rownum'] = $paihang[0]['rownum'] - 1;
                $this->assign('paihang',$paihang);
            }else{
                if($last['rownum'] == ''){
                    $last = end($list);
                }
                $paihang[0]['rownum'] = $last['rownum']+1;
                $paihang[0]['logo'] = $user['logo'];
                $this->assign('paihang',$paihang);
            }

            $this->assign('list',$list);
//            $this->assign('paihang',array_values($paihang));
            unset($list[0]);
            unset($list[1]);
            unset($list[2]);
            $this->assign('m_list',$list);
        }else if($type == 4){               //年榜
            $data = $this->getYear();
            //占位排名
            $sql = "SELECT obj_new.*,a.realname,a.logo,a.mobile FROM ys_user as a left join ((SELECT obj.uid, obj.timestampsum, @rownum := @rownum + 1 AS num_tmp, @incrnum := CASE WHEN @rowtotal = obj.timestampsum THEN @incrnum WHEN @rowtotal := obj.timestampsum THEN  @rownum END AS rownum FROM   (SELECT uid, sum(point) as timestampsum, addtime FROM  `ys_user_point_log` where  addtime>".$data['start']." and addtime<".$data['end']." group by uid order by timestampsum desc ) AS obj , ( SELECT @rownum := 0 ,@rowtotal := NULL ,@incrnum := 0 ) r order by timestampsum desc ) AS obj_new) on obj_new.uid=a.uid  order by  timestampsum desc ";

//            $sql = "SELECT obj_new.*,a.realname,a.logo,a.mobile FROM ys_user as a left join ((SELECT obj.uid, obj.timestampsum, @rownum := @rownum + 1 AS num_tmp, @incrnum := CASE WHEN @rowtotal = obj.timestampsum THEN @incrnum WHEN @rowtotal := obj.timestampsum THEN  @rownum END AS rownum FROM   (SELECT uid, sum(point) as timestampsum, addtime FROM  `ys_user_point_log` where  addtime>".$data['start']." and addtime<".$data['end']." group by uid order by timestampsum desc ) AS obj , ( SELECT @rownum := 0 ,@rowtotal := NULL ,@incrnum := 0 ) r order by timestampsum desc ) AS obj_new) on obj_new.uid=a.uid  order by  timestampsum desc";


//            $sql = "SELECT obj.timestampsum,a.uid,a.mobile,a.realname,@rownum := @rownum + 1 AS rownum FROM ys_user as a right join (SELECT uid, sum(point) as timestampsum, addtime FROM  `ys_user_point_log` where  addtime>".$data['start']." and addtime<".$data['end']." group by uid order by timestampsum desc ) AS obj on a.uid=obj.uid, (SELECT @rownum := 0) r ";

            $list = Db::query($sql);

            $uid = session('_user_uid_.uid');
            $paihang = array_filter($list, function($t) use ($uid) { return $t['uid'] == $uid; });
            $list = array_slice($list,0,10);
            foreach($list as $k => $v){
                if($k == 1){
                    $list[$k]['rownum'] = 2;
                    continue;
                }
                if($k == 2){
                    $list[$k]['rownum'] = 3;
                    continue;
                }
                if($k != 0){
                    $up_k = $k-1;
                    if($v['timestampsum'] == $list[$up_k]['timestampsum']){
                        $list[$k]['rownum'] = $list[$up_k]['rownum'];
                    }else{
                        $list[$k]['rownum'] = $list[$up_k]['rownum']+1;
                    }
                }else{
                    $list[$k]['rownum'] = 1;
                }
            }

            if(!empty(array_values($paihang))){
                $paihang = array_values($paihang);
                $paihang[0]['rownum'] = $paihang[0]['rownum'] - 1;
                $this->assign('paihang',$paihang);
            }else{
                if($last['rownum'] == ''){
                    $last = end($list);
                }
                $paihang[0]['rownum'] = $last['rownum']+1;
                $paihang[0]['logo'] = $user['logo'];
                $this->assign('paihang',$paihang);
            }

            $this->assign('list',$list);
//            $this->assign('paihang',array_values($paihang));

            unset($list[0]);
            unset($list[1]);
            unset($list[2]);
            $this->assign('m_list',$list);

        }
        $this->assign('store',$store);
        $this->assign('type',$type);
    }

    /**
     * @Author  lingyun
     * @Desc    我的积分详情
     * 2018-05-05
     */
    public function my_point_log(){
        $store = db('store')->where('id',cookie('store_id'))->find();
        $cur_page = empty(input('page'))?1:input('page');           //当前的页码
        $uid = session('_user_uid_.uid');
//        $list = db('user_point_log')->where(['uid'=>$uid,'store_id'=>cookie('store_id')])->order('id desc')->paginate(10,false,['query'=>request()->param()]);
        $list = db('user_point_log')->where(['uid'=>$uid])->order('id desc')->paginate(10,false,['query'=>request()->param()]);
        $count = db('user_point_log')->where(['uid'=>$uid,'store_id'=>cookie('store_id')])->count();
        $page = $list->render();
        $this->assign('page',$page);
        $this->assign('list',$list);
        $this->assign('all_page',ceil($count/10));
        $this->assign('cur_page',$cur_page);
        $this->assign('store',$store);
    }

    /**
     * @Author  lingyun
     * @Desc    ajax获取积分详情
     */
    public function get_ajax_point_log($page){
        $page = $page+1;
        $result = db('user_point_log')->alias('a')->where(['a.uid'=>session('_user_uid_.uid'),'a.store_id'=>cookie('store_id')])->field('a.*,FROM_UNIXTIME(a.addtime,"%Y.%m.%d") as add_time')->page($page,10)->select();
        if(empty($result)){     //到底了
            $this->success($page-1,'',$result);
        }
        $this->success($page,'',$result);
    }

    /**
     * @Author  lingyun
     * @Desc    获取本周的起止时间
     * @return array
     */
    private function get_week(){
        $now = time();
        $time = ('1' == date('w')) ? strtotime('Monday', $now) : strtotime('last Monday', $now);
        $start = date('Y-m-d 00:00:00', $time);
        $end = date('Y-m-d 23:59:59', strtotime('Sunday', $now));
        return ['start'=>strtotime($start),'end'=>strtotime($end)];
    }

    /**
     * @Author  lingyun
     * @Desc    获取本月的起止时间
     * @param int $month
     * @return array
     */
    private function getMonth($month=0){
        $y = date('Y',time());      //获取年份
        if($month == 0){
            $m = date('m',time());
            $month = $y."-".$m;
            $start=strtotime($month);
            $end=mktime(23, 59, 59, date('m', strtotime($month))+1, 00);
            return array('start'=>$start,'end'=>$end);
        }else{
            $m = $y."-".$month;
            $start=strtotime($m);
            $end=mktime(23, 59, 59, date('m', strtotime($m))+1, 00);
            return array('start'=>$start,'end'=>$end);
        }
    }
    /**
     * 获取今年的时间戳
     * @Author   lingyun
     * @DateTime 2017-12-08T19:51:11+0800
     * @return   [type]                   [description]
     */
    private function getYear(){
        $date = date('Y',time());       //2017-12-08 19:54:18
        $start = strtotime($date."-1-1 00:00:00");
        $end = strtotime($date."-12-31 23:59:59");
        return array('start'=>$start,'end'=>$end);
    }

    /**
     * @Author  lingyun
     * @Desc    修改会员信息
     * PC端完善个人信息
     */
    public function edit_member_info(){
        $post = input('post.');
        $images = '';
        $accessKey = config('qiniu.accesskey');//七牛云accesskey
        $secretKey = config('qiniu.secretkey');//七牛云secretkey
        $bucket = config('qiniu.bucket');//七牛云存储空间
        $url = config('qiniu.backurl');//七牛云绑定的域名默认为测试域名

        if(!empty($post['logo'])){           //
            preg_match('/^(data:\s*image\/(\w+);base64,)/', trim($post['logo']), $result1);
            $base64 = str_replace($result1[1], '', trim($post['logo']));

            $qiniu = new Qiniu($accessKey,$secretKey,$bucket);
            $ret = $qiniu->baseUplod($base64,$bucket);

            if ($ret) {
                $data_arr['logo'] = $url.'/'.$ret;
            }
        }
        $data_arr['realname'] = $post['realname'];
        $data_arr['nickname'] = $post['realname'];
        $data_arr['sex'] = $post['sex'];
        $data_arr['birthday_year'] = $post['birth_year'];
        $data_arr['birthday_month'] = $post['birth_month'];
        $data_arr['birthday_day'] = $post['birth_day'];
        session('_user_uid_.realname',$data_arr['realname']);
        $res = db('user')->where('uid',session('_user_uid_.uid'))->update($data_arr);
        $res!==false?$this->success('修改成功',''):$this->error('修改失败','');
    }

    /**
     * @Author  lingyun
     * @Desc    移动端完善会员信息
     * 2018-05-10
     */
    public function m_edit_member_info(){
        $post = input('post.');
//        halt($post);
        $images = '';
        $accessKey = config('qiniu.accesskey');//七牛云accesskey
        $secretKey = config('qiniu.secretkey');//七牛云secretkey
        $bucket = config('qiniu.bucket');//七牛云存储空间
        $url = config('qiniu.backurl');//七牛云绑定的域名默认为测试域名

        if(!empty($post['logo'])){           //
            preg_match('/^(data:\s*image\/(\w+);base64,)/', trim($post['logo']), $result1);
            $base64 = str_replace($result1[1], '', trim($post['logo']));

            $qiniu = new Qiniu($accessKey,$secretKey,$bucket);
            $ret = $qiniu->baseUplod($base64,$bucket);
            if ($ret) {
                $data_arr['logo'] = $url.'/'.$ret;
            }
        }
        $data_arr['realname'] = $post['realname'];
        $data_arr['nickname'] = $post['realname'];
        $data_arr['sex'] = $post['sex'];
        session('_user_uid_.realname',$post['realname']);
        if(!empty($post['birthday'])){
            $birthday = explode('-',$post['birthday']);
            $data_arr['birthday_year'] = $birthday[0];
            $data_arr['birthday_month'] = $birthday[1];
            $data_arr['birthday_day'] = $birthday[2];
        }else{
            $data_arr['birthday_year'] = '';
            $data_arr['birthday_month'] = '';
            $data_arr['birthday_day'] = '';
        }

        $res = db('user')->where('uid',session('_user_uid_.uid'))->update($data_arr);
        $res!==false?$this->success('修改成功',''):$this->error('修改失败','');
    }

    /**
     * @Author  lingyun
     * @Desc    检查订单信息
     */
    public function edit_password(){
        $post = input('post.');
        if(empty($post['old_password'])){
            $this->error('请输入原始密码','');
        }

        $reg = '/^[a-zA-Z0-9_]{6,16}$/';
        if(empty($post['password'])){
            $this->error('请输入新密码','');
        }

        if(!preg_match($reg,$post['password'])){
            $this->error('新密码输入有误，必须是字母数字下划线6~16位组合','');
        }

        if(empty($post['repassword'])){
            $this->error('请输入确认密码','');
        }
        if($post['password'] !== $post['repassword']){
            $this->error('两次密码输入不一致，请重新输入','');
        }

        $member = db('user')->where('uid',session('_user_uid_.uid'))->find();
        if($member['password'] != md5($post['password'])){
            $this->error('原始密码输入错误，请重新输入');
        }

        $data_arr = [
            'password'=>md5($post['password'])
        ];
        $res = db('user')->where('uid',session('_user_uid_.uid'))->update($data_arr);
        $res!==false?$this->success('保存成功',''):$this->error('保存失败','');
    }

    /**
     * @Author  lingyun
     * @Desc    修改手机号
     * 2018-05-10
     */
    public function edit_mobile(){
        $post = input('post.');
        $send_time = session('mobile_send_time');
        $code = session('mobile_sms_code');
        $mobile_msg_mobile = session('mobile_msg_mobile');
        $reg = '/^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/';

        if(empty($post['old_mobile'])){
            $this->error('请输入原手机号','');
        }
        if(empty($post['mobile'])){
            $this->error('请输入新手机号','');
        }
        if(empty($post['msg_code'])){
            $this->error('请输入验证码','');
        }
        if(!preg_match($reg,$post['mobile'])){
            $this->error('手机号格式输入有误，请重新输入','');
        }
        if($send_time+7200 < time()){
            $this->error('验证码已过期，请重新输入','');
        }
        if($post['mobile'] != $mobile_msg_mobile){
            $this->error('该手机号未接收验证码，请获取验证码','');
        }
        if($post['msg_code'] != $code){
            $this->error('验证码输入错误，请重新输入','');
        }
        if($post['mobile'] == $post['old_mobile']){
            $this->error('新手机号不能和原手机号相同','');
        }
        $member = db('user')->where('uid',session('_user_uid_.uid'))->find();
        if($member['mobile'] != $post['old_mobile']){
            $this->error('原手机号输入不正确，请重新输入','');
        }

        $falg = db('user')->where('mobile',$post['mobile'])->find();
        if(!empty($falg)){
            $this->error('该手机号已经注册，请换其它手机');
        }

        $res = db('user')->where('uid',session('_user_uid_.uid'))->update(['mobile'=>$post['mobile']]);
        $res!==false?$this->success('修改成功',''):$this->error('修改失败','');
    }

    /**
     * @Author  lingyun
     * @Desc    获取短信验证码 - 修改手机号
     * 2018-05-10
     */
    public function get_msg_code(){
        $mobile = input('mobile');      //获取手机号
        $send_time = session('mobile_send_time');
        if(!empty($send_time) && $send_time+60>time()){
            $this->error('验证码请求过于频繁，请稍后再试','');
        }
        $code = rand(100000,999999);
        $response = \SMS::sendSms(config('alidayu.msg_sign'),config('alidayu.msg_template'),$mobile,array("code"=>$code)
        );

        if($response->Code == 'OK'){
            session('mobile_sms_code',$code);
            session('mobile_msg_mobile',$mobile);
            session('mobile_send_time',time());
//            Cache::set('18765227746'.'sms_code',868686,60);
            $this->success('发送成功','',array('code'=>$code));
        }else{
            $this->error('发送失败，请稍后再试','');
        }
    }

}